package com.chenailin.www.daoimpl;

import com.chenailin.www.dao.DoctorDAO;
import com.chenailin.www.pojo.Doctor;
import com.chenailin.www.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DoctorDAOImpl implements DoctorDAO {

    // 添加医生
    @Override
    public boolean addDoctor(Doctor doctor) throws SQLException {
        String sql = "INSERT INTO doctors (id, name, department_id) VALUES (?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, doctor.getDocId());
            ps.setString(2, doctor.getDocName());
            ps.setInt(3, doctor.getDepartmentId());
            return ps.executeUpdate() > 0;
        } catch (SQLException e) {
            System.err.println("数据库操作失败: " + e.getMessage());
            return false;
        }
    }

    // 修改医生
    @Override
    public boolean modifyDoctor(Doctor doctor) throws SQLException {
        String sql = "UPDATE doctors SET name = ?, department_id = ? WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, doctor.getDocName());
            ps.setInt(2, doctor.getDepartmentId());
            ps.setInt(3, doctor.getDocId());
            //受影响的行数
            int affectedRows = ps.executeUpdate();
            return affectedRows > 0;
        } catch (SQLException e) {
            System.err.println("数据库操作失败: " + e.getMessage());
            return false;
        }
    }

    // 删除医生
    @Override
    public boolean deleteDoctor(int doctorId) throws SQLException {
        String sql = "DELETE FROM doctors WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, doctorId);
            //受影响的行数
            int affectedRows = ps.executeUpdate();
            return affectedRows > 0;
        } catch (SQLException e) {
            System.err.println("数据库操作失败: " + e.getMessage());
            return false;
        }
    }

    // 添加时间段
    @Override
    public boolean addSchedule(int doctorId, List<Integer> schedule) throws SQLException {
        if(schedule == null || schedule.isEmpty()) return false;
        String sql = "INSERT INTO doctor_schedule (id, schedule) VALUES (?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            for(Integer slot : schedule) {
                ps.setInt(1, doctorId);
                ps.setInt(2, slot);
                ps.addBatch();      // 添加批处理任务
            }
            ps.executeBatch();
            return true;
        } catch (SQLException e) {
            System.err.println("数据库操作失败: " + e.getMessage());
            return false;
        }
    }

    // 删除时间段
    @Override
    public boolean deleteSchedule(int doctorId, List<Integer> schedule) throws SQLException {
        if(schedule == null || schedule.isEmpty()) return false;
        String sql = "DELETE FROM doctor_schedule WHERE id = ? AND schedule = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            for(Integer slot : schedule) {
                ps.setInt(1, doctorId);
                ps.setInt(2, slot);
                ps.addBatch(); // 添加批处理
            }
            int[] results = ps.executeBatch();
            // 检查是否所有删除都成功
            for (int result : results) {
                if (result == Statement.EXECUTE_FAILED) {
                    return false;
                }
            }
            return true;
        } catch (SQLException e) {
            System.err.println("数据库操作失败: " + e.getMessage());
            return false;
        }
    }

    // 删除所有时间段
    @Override
    public boolean deleteAllSchedule(int doctorId) throws SQLException {
        String sql = "DELETE FROM doctor_schedule WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, doctorId);
            int affectedRows = ps.executeUpdate();
            return affectedRows > 0;
        } catch (SQLException e) {
            System.err.println("数据库操作失败: " + e.getMessage());
            return false;
        }
    }

    // 查看所有医生 ???
    @Override
    public List<Doctor> getAllDoctors() {
        List<Doctor> list = new ArrayList<>();
        String sql = "SELECT * FROM doctors";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    list.add(new Doctor(rs.getString("name"),
                            rs.getInt("id"),
                            rs.getInt("department_id"),
                            getSchedule((rs.getInt("id")))));
                }
            }
            return list;
        } catch (SQLException e) {
            System.err.println("数据库操作失败: " + e.getMessage());
            return null;
        }
    }

    // 查询医生有空的时间段
    @Override
    public List<Integer> getUnSelectedSchedule(int docId) {
        List<Integer> slots = new ArrayList<>();
        String sql = "SELECT schedule FROM doctor_schedule WHERE id = ? AND selected = 0";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, docId);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                slots.add(rs.getInt("schedule"));
            }
            return slots;
        } catch (SQLException e) {
            System.err.println("数据库操作失败: " + e.getMessage());
            return null;
        }
    }

    // 查询医生所有时间段
    @Override
    public List<Integer> getSchedule(int docId) throws SQLException {
        List<Integer> slots = new ArrayList<>();
        String sql = "SELECT schedule FROM doctor_schedule WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, docId);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                slots.add(rs.getInt("schedule"));
            }
            return slots;
        } catch (SQLException e) {
            System.err.println("数据库操作失败: " + e.getMessage());
            return null;
        }
    }

    // 查询相应部门下是否有人
    @Override
    public boolean countByDepartment(int departId) {
        String sql = "SELECT COUNT(*) FROM doctors WHERE departId = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, departId);
            try (ResultSet rs = ps.executeQuery()){
                return rs.next() && rs.getInt(1) > 0;
            }
        } catch (SQLException e) {
            System.err.println("数据库操作失败: " + e.getMessage());
            return false;
        }
    }

    // 查找对应部门的所有医生  初始值是空吗
    public List<Doctor> findDoctorByDepartment(int departId) throws SQLException {
        List<Doctor> doctors = new ArrayList<>();
         String sql = "SELECT * FROM doctors WHERE department_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, departId);
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    doctors.add(new Doctor(rs.getString("name"),
                            rs.getInt("id"),
                            rs.getInt("department_id"),
                            getSchedule(rs.getInt("id"))));
                }
            }
            return doctors;
        } catch (SQLException e) {
            System.err.println("数据库操作失败: " + e.getMessage());
            return null;
        }
    }

    // 根据编号查找医生
    @Override
    public Doctor findById(int id) {
        String sql = "SELECT * FROM doctors WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, id);
            try (ResultSet rs = ps.executeQuery()){
                if(rs.next()) {
                    return new Doctor(rs.getString("name"),
                            rs.getInt("id"),
                            rs.getInt("department_id"),
                            getSchedule(rs.getInt("id")));
                }
                return null;
            }
        } catch (SQLException e) {
            System.err.println("数据库操作失败: " + e.getMessage());
            return null;
        }
    }

    // 判断医生是否有空
    @Override
    public boolean isDoctorAvailable(int doctorId, int slot) {
        String sql = "SELECT 1 FROM doctor_schedule WHERE id = ? AND schedule = ? AND selected = 0";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, doctorId);
            ps.setInt(2, slot);
            try (ResultSet rs = ps.executeQuery()) {
                return rs.next();
            }
        } catch (SQLException e) {
            System.err.println("数据库操作失败: " + e.getMessage());
            return false;
        }
    }

}
